import { _decorator, Animation, Collider2D, Component, Contact2DType, Node, IPhysics2DContact, RigidBody2D, RigidBody, Sprite, AudioClip } from 'cc';
import { Bullet } from './Bullet';
import { GameManager } from './GameManager';
import { EnemyManager } from './EnemyManager';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {
    @property
    speed:number = 300;
    @property(Animation)
    anim: Animation = null;
    @property(Collider2D)
    collider: Collider2D = null;
    @property
    hp: number = 1;
    @property
    animHit: string = '';
    @property
    animDown: string = '';
    @property
    score: number = 0;
    isDead: boolean = false;

    @property(AudioClip)
    enemyDownAudio: AudioClip = null;
    start() {
        if(this.collider){
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if(otherCollider.getComponent(Bullet)){
            otherCollider.enabled = false;
            otherCollider.getComponent(Sprite).enabled = false;
        }
        this.hp -= 1;
        if(this.hp > 0){
            this.anim.play(this.animHit);
        }
        if(this.hp <= 0){
            this.die();   
        }
    }

    update(deltaTime: number) {
        if(this.hp > 0){
            const position = this.node.position;
            this.node.setPosition(position.x, position.y - this.speed * deltaTime, position.z);
        }

        if(this.node.getPosition().y < -580){
            this.node.destroy();
        }
    }

    die() {
        if(this.isDead) return;
        this.anim.play(this.animDown);
        AudioMgr.inst.playOneShot(this.enemyDownAudio);
        GameManager.getInstance().addScore(this.score);
        if(this.collider){
            this.collider.enabled = false;
        }
        
        this.scheduleOnce(() => {
            this.node.destroy()
        }, 1)
        this.isDead = true;
    }

    protected onDestroy(): void {
        if(this.collider){
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
        this.isDead = true;
        EnemyManager.getInstance().removeEnemy(this.node);
    }
}


